Page({
  data: {

    tabs: [
      { key: 'all', label: '全部', count: 0 },
      { key: 'waiting_team', label: '待接单', count: 0 },
      { key: 'team_accepted', label: '已接单', count: 0 },
      { key: 'surveying', label: '查勘中', count: 0 },
      { key: 'designing', label: '设计中', count: 0 },
      { key: 'quoted', label: '已报价', count: 0 },
      { key: 'in_progress', label: '施工中', count: 0 },
      { key: 'testing', label: '验收中', count: 0 },
      { key: 'completed', label: '已完成', count: 0 },
      { key: 'cancelled', label: '已取消', count: 0 }
    ],
    // 服务类目映射表 - 基于实际业务场景
    serviceCategoryMap: {
      'sme_market': { name: '中小市场服务', icon: '🏢', color: '#1976D2' },
      'info_integration': { name: '信息化集成', icon: '💻', color: '#673AB7' },
      'engineering': { name: '工程施工', icon: '🏗️', color: '#FF6B35' },
      'network_maintenance': { name: '网络维护', icon: '🔧', color: '#00ACC1' },
      'smart_home': { name: '智能家居', icon: '🏠', color: '#4CAF50' },
      'measurement': { name: '计量检测', icon: '📏', color: '#FF9800' },
      'materials': { name: '材料设备', icon: '📦', color: '#795548' },
      'construction_team': { name: '施工队伍', icon: '👷', color: '#F44336' },
      // 兼容旧数据的通用类目
      'home_service': { name: '家居服务', icon: '🏠', color: '#4CAF50' },
      'repair_service': { name: '维修服务', icon: '🔧', color: '#00ACC1' },
      'decoration': { name: '装修服务', icon: '🎨', color: '#9C27B0' },
      'cleaning': { name: '清洁服务', icon: '🧹', color: '#2196F3' },
      'appliance': { name: '家电服务', icon: '📺', color: '#FF9800' },
      'plumbing': { name: '水电服务', icon: '💧', color: '#03A9F4' },
      'default': { name: '专业服务', icon: '⚙️', color: '#666666' }
    },
    activeTab: 'all',
    tabScrollLeft: 0, // 标签栏滚动位置
    orders: [],
    filteredOrders: [],
          statusMap: {
        // 与标签栏完全对应的状态映射
        'waiting_team': { text: '待接单', color: '#FF6B35', bgColor: 'rgba(255, 107, 53, 0.1)' },
        'team_accepted': { text: '已接单', color: '#2196F3', bgColor: 'rgba(33, 150, 243, 0.1)' },
        'surveying': { text: '查勘中', color: '#9C27B0', bgColor: 'rgba(156, 39, 176, 0.1)' },
        'designing': { text: '设计中', color: '#673AB7', bgColor: 'rgba(103, 58, 183, 0.1)' },
        'quoted': { text: '已报价', color: '#3F51B5', bgColor: 'rgba(63, 81, 181, 0.1)' },
        'in_progress': { text: '施工中', color: '#2196F3', bgColor: 'rgba(33, 150, 243, 0.1)' },
        'testing': { text: '验收中', color: '#00BCD4', bgColor: 'rgba(0, 188, 212, 0.1)' },
        'completed': { text: '已完成', color: '#4CAF50', bgColor: 'rgba(76, 175, 80, 0.1)' },
        'cancelled': { text: '已取消', color: '#F44336', bgColor: 'rgba(244, 67, 54, 0.1)' },
        
        // 兼容旧状态的映射
        'pending': { text: '待接单', color: '#FF6B35', bgColor: 'rgba(255, 107, 53, 0.1)' },
        'confirmed': { text: '已接单', color: '#2196F3', bgColor: 'rgba(33, 150, 243, 0.1)' },
        'team_preparing': { text: '已接单', color: '#2196F3', bgColor: 'rgba(33, 150, 243, 0.1)' },
        'team_on_site': { text: '施工中', color: '#2196F3', bgColor: 'rgba(33, 150, 243, 0.1)' },
        'paused': { text: '施工中', color: '#FF9800', bgColor: 'rgba(255, 152, 0, 0.1)' },
        'rejected': { text: '已取消', color: '#F44336', bgColor: 'rgba(244, 67, 54, 0.1)' },
        'reassigning': { text: '待接单', color: '#FF9800', bgColor: 'rgba(255, 152, 0, 0.1)' },
        
        // 英文状态映射
        'accepted': { text: '已接单', color: '#2196F3', bgColor: 'rgba(33, 150, 243, 0.1)' },
        'waiting': { text: '待接单', color: '#FF6B35', bgColor: 'rgba(255, 107, 53, 0.1)' },
        'progress': { text: '施工中', color: '#2196F3', bgColor: 'rgba(33, 150, 243, 0.1)' },
        'finished': { text: '已完成', color: '#4CAF50', bgColor: 'rgba(76, 175, 80, 0.1)' },
        'canceled': { text: '已取消', color: '#F44336', bgColor: 'rgba(244, 67, 54, 0.1)' }
      },
    loading: false,
    refreshing: false,
    hasMore: true,
    page: 0,
    pageSize: 5, // 首次只加载5条
    loadMoreSize: 10, // 后续每次加载10条
    // 用户相关数据
    currentUser: null,
    userDisplayId: null,
    isLoggedIn: false,
    loginChecked: false,
    searchKeyword: '',
    showFilterMenu: false,
    showOrderMenu: false,
    selectedOrderId: '',
    sortBy: 'createTime',
    sortOrder: 'desc',
    timeRange: 'all',
    stats: {
      total: 0,
      pending: 0,
      inProgress: 0,
      completed: 0
    },
    urgencyMap: {
      'low': { text: '一般', color: '#4CAF50' },
      'medium': { text: '紧急', color: '#FF9800' },
      'high': { text: '特急', color: '#F44336' }
    },
    sortOptions: [
      { key: 'createTime', label: '创建时间' },
      { key: 'updateTime', label: '更新时间' },
      { key: 'status', label: '状态' },
      { key: 'customerName', label: '客户姓名' }
    ],
    timeRangeOptions: [
      { key: 'all', label: '全部时间' },
      { key: 'today', label: '今天' },
      { key: 'week', label: '本周' },
      { key: 'month', label: '本月' },
      { key: 'quarter', label: '本季度' }
    ]
  },

  async onLoad(options) {
    // 页面标题设置为"我的订单"
    wx.setNavigationBarTitle({
      title: '我的订单'
    })

    // 处理URL参数，设置初始标签页
    if (options && options.tab) {
      console.log('📋 接收到标签页参数:', options.tab)
      // 验证标签页是否有效
      const validTabs = this.data.tabs.map(tab => tab.key)
      if (validTabs.includes(options.tab)) {
        this.setData({
          activeTab: options.tab
        })
        console.log('✅ 设置初始标签页:', options.tab)
      } else {
        console.warn('⚠️ 无效的标签页参数:', options.tab)
      }
    }
    
    // 检查登录状态
    await this.checkLoginStatus()
  },

  async onShow() {
    // 处理从其他页面跳转过来的标签页参数
    this.handleTabParameter()
    
    // 每次显示页面时重新检查登录状态
    await this.checkLoginStatus()
  },

  // 处理标签页参数（支持从其他页面跳转）
  handleTabParameter() {
    // 检查全局变量中是否有目标标签页
    const app = getApp()
    const targetTab = app.globalData.targetTab
    
    if (targetTab) {
      console.log('📋 从全局变量接收到标签页参数:', targetTab)
      
      // 验证标签页是否有效
      const validTabs = this.data.tabs.map(tab => tab.key)
      if (validTabs.includes(targetTab) && this.data.activeTab !== targetTab) {
        console.log('✅ 切换到目标标签页:', targetTab)
        this.setData({
          activeTab: targetTab
        })
        
        // 如果已经有订单数据，立即应用过滤器
        if (this.data.orders.length > 0) {
          this.filterOrders()
        }
        
        // 滚动到目标标签页
        this.scrollToTab(targetTab)
      }
      
      // 清除全局变量，避免重复处理
      app.globalData.targetTab = null
    }
    
    // 兼容URL参数方式（保留原有逻辑）
    const pages = getCurrentPages()
    const currentPage = pages[pages.length - 1]
    
    if (currentPage && currentPage.options && currentPage.options.tab) {
      const urlTab = currentPage.options.tab
      console.log('📋 从URL接收到标签页参数:', urlTab)
      
      // 验证标签页是否有效
      const validTabs = this.data.tabs.map(tab => tab.key)
      if (validTabs.includes(urlTab) && this.data.activeTab !== urlTab) {
        console.log('✅ 切换到URL标签页:', urlTab)
        this.setData({
          activeTab: urlTab
        })
        
        // 如果已经有订单数据，立即应用过滤器
        if (this.data.orders.length > 0) {
          this.filterOrders()
        }
        
        // 滚动到目标标签页
        this.scrollToTab(urlTab)
      }
      
      // 清除URL参数，避免重复处理
      currentPage.options.tab = null
    }
  },

  // 🔐 检查登录状态（简化版本）
  async checkLoginStatus() {
    console.log('🔐 检查登录状态...')
    
    try {
      // 检查本地登录状态
      const isLoggedIn = wx.getStorageSync('isLoggedIn')
      const userInfo = wx.getStorageSync('userInfo')
      
      if (!isLoggedIn || !userInfo || !userInfo.openid) {
        console.log('❌ 本地登录状态无效')
        this.setLoginStatus(false, '本地登录状态无效')
        return
      }
      
      // 检查微信session（可选，不阻塞）
      wx.checkSession({
        success: () => {
          console.log('✅ 微信session有效')
        },
        fail: () => {
          console.log('⚠️ 微信session已过期，但不影响使用')
        }
      })
      
      // 设置登录状态
      this.setLoginStatus(true, '登录状态有效', userInfo)
      
      // 加载订单数据
      await this.loadOrders()
      
    } catch (error) {
      console.error('❌ 登录检查出错:', error)
      this.setLoginStatus(false, '登录检查出错: ' + error.message)
    }
  },

  // 设置登录状态
  setLoginStatus(isLoggedIn, reason, userInfo = null) {
    console.log(`🔐 设置登录状态: ${isLoggedIn ? '已登录' : '未登录'} - ${reason}`)
    
    this.setData({
      isLoggedIn: isLoggedIn,
      loginChecked: true,
      currentUser: userInfo,
      userDisplayId: userInfo ? (userInfo.displayId || userInfo.numericId || userInfo.openid) : null
    })
    
    if (!isLoggedIn) {
      // 未登录时清空订单数据
      this.clearOrderData()
    }
  },

  // 清空订单数据
  clearOrderData() {
    this.setData({
      orders: [],
      filteredOrders: [],
      stats: {
        total: 0,
        pending: 0,
        inProgress: 0,
        completed: 0
      }
    })
    this.updateTabCounts()
  },

  // 显示登录提示和跳转
  showLoginModal() {


    wx.showModal({
      title: '需要登录',
      content: '查看订单需要先登录，是否立即前往登录？',
      confirmText: '去登录',
      cancelText: '取消',
      success: (res) => {
        if (res.confirm) {
          // 保存当前页面信息到全局存储
          const returnUrl = '/pages/orders/orders'
          wx.setStorageSync('loginReturnUrl', returnUrl)
    

          // 跳转到个人中心
          wx.switchTab({
            url: '/pages/profile/profile'
          })
        }
      }
    })
  },

  // 🔐 验证登录状态的装饰器方法
  requireLogin(callback) {
    if (!this.data.isLoggedIn || !this.data.loginChecked) {
      console.log('❌ 操作需要登录，当前状态检查失败')
      this.showLoginModal()
      return false
    }
    
    if (typeof callback === 'function') {
      return callback()
    }
    
    return true
  },

  // 跳转到预约页面
  goToBooking() {
    wx.switchTab({
      url: '/pages/index/index'
    })
  },

  onPullDownRefresh() {
    this.refreshOrders()
  },

  onReachBottom() {
    console.log('📖 触发onReachBottom，当前状态:', {
      hasMore: this.data.hasMore,
      loading: this.data.loading,
      page: this.data.page,
      ordersCount: this.data.orders.length
    })
    this.loadMoreOrders()
  },

  // 刷新订单数据
  async refreshOrders() {
    if (!this.requireLogin()) {
      wx.stopPullDownRefresh()
      return
    }
    
    this.setData({
      refreshing: true,
      page: 0,
      hasMore: true
    })
    
    await this.loadOrders(true)
    
    this.setData({ refreshing: false })
    wx.stopPullDownRefresh()
  },

  // 加载更多订单
  async loadMoreOrders() {
    if (!this.data.hasMore || this.data.loading) {
      console.log('📖 跳过加载更多:', { loading: this.data.loading, hasMore: this.data.hasMore })
      return
    }

    if (!this.requireLogin()) {
      return
    }

    console.log('📖 懒加载更多订单...')
    const nextPage = this.data.page + 1
    this.setData({ page: nextPage })
    await this.loadOrders(false, nextPage)
  },

  // 加载订单数据 - 使用云函数
  async loadOrders(refresh = true, page = 0) {
    if (this.data.loading) return
    
    // 严格检查登录状态
    if (!this.data.isLoggedIn || !this.data.currentUser) {
      console.log('❌ 用户未登录或状态无效，无法加载订单')
      this.clearOrderData()
      return
    }
    
    this.setData({ loading: true })

    try {
      // 🚀 懒加载逻辑：首次加载5条，后续加载10条
      const isFirstLoad = refresh || page === 0
      const currentLimit = isFirstLoad ? this.data.pageSize : this.data.loadMoreSize
      const currentSkip = isFirstLoad ? 0 : this.data.pageSize + (page - 1) * this.data.loadMoreSize
      
      console.log(`📋 懒加载订单: ${isFirstLoad ? '首次' : '加载更多'}, limit=${currentLimit}, skip=${currentSkip}, activeTab=${this.data.activeTab}`)
      
      const callData = {
        action: 'getUserOrders',
        status: this.data.activeTab,
        limit: currentLimit,
        skip: currentSkip
      }
      console.log('🚀 发送云函数参数:', callData)
  
      const result = await wx.cloud.callFunction({
        name: 'businessManager',
        data: callData
      })

      if (result.result.success) {
        let newOrders = result.result.data
        
        // 🔍 安全检查：验证返回的订单是否都属于当前用户
        const currentUserOpenId = wx.getStorageSync('userInfo')?.openid
        console.log('🔐 当前用户openid:', currentUserOpenId)
        
        if (currentUserOpenId) {
          const wrongOrders = newOrders.filter(order => order.openid !== currentUserOpenId)
          if (wrongOrders.length > 0) {
            console.error('🚨 发现其他用户的订单数据，安全风险！', wrongOrders.map(o => ({ id: o.id, openid: o.openid })))
            wx.showModal({
              title: '数据安全警告',
              content: `检测到${wrongOrders.length}个不属于您的订单，已自动过滤。如问题持续，请联系客服。`,
              showCancel: false
            })
            // 过滤掉不属于当前用户的订单
            newOrders = newOrders.filter(order => order.openid === currentUserOpenId)
          } else {
            console.log('✅ 订单数据安全检查通过，所有订单都属于当前用户')
          }
        }
        
        let orders = []

        if (refresh || page === 0) {
          orders = newOrders
        } else {
          // 需要先将现有orders的预处理数据去掉，再合并新数据
          const existingOrders = this.data.orders.map(order => {
            // 移除之前添加的预处理字段，保持数据纯净
            const { categoryInfo, projectName, serviceImage, formattedCreateTime, formattedUpdateTime, ...cleanOrder } = order
            return cleanOrder
          })
          orders = [...existingOrders, ...newOrders]
        }

        // 🚀 懒加载：判断是否还有更多数据
        const hasMore = newOrders.length === currentLimit
        console.log(`📊 懒加载状态: 返回${newOrders.length}条, 期望${currentLimit}条, hasMore=${hasMore}`)

        // 预处理订单数据，添加服务信息
        const processedOrders = orders.map(order => {
          const categoryInfo = this.getServiceCategoryInfo(order)
          const projectName = this.getServiceProjectName(order)
          const serviceImage = this.getServiceImage(order)
          

          
          // 预处理时间字段
          const timeValue = order.createTime || order._createTime || order.createdAt || order.timestamp
          const formattedCreateTime = this.formatCreateTime(timeValue)
          

          
          // 预处理更新时间
          const updateTimeValue = order.updateTime || order._updateTime || order.updatedAt
          const formattedUpdateTime = updateTimeValue && updateTimeValue !== timeValue ? this.formatDate(updateTimeValue) : null
          
          return {
            ...order,
            // 添加处理后的服务信息
            categoryInfo: categoryInfo,
            projectName: projectName,
            serviceImage: serviceImage,
            // 添加格式化后的时间
            formattedCreateTime: formattedCreateTime,
            formattedUpdateTime: formattedUpdateTime
          }
        })

        this.setData({
          orders: processedOrders,
          hasMore: hasMore,
          page: page
        })

        this.filterOrders()
        this.updateTabCounts()
        this.updateStats()
        

      } else {
        console.error('❌ 加载订单失败:', result.result.error)
        wx.showToast({
          title: result.result.error || '加载失败',
          icon: 'none'
        })
      }
    } catch (error) {
      console.error('❌ 加载订单异常:', error)
      
      // 🚫 移除降级到本地存储的逻辑，强制要求登录
      wx.showToast({
        title: '网络异常，请重试',
        icon: 'none'
      })
      
      // 如果是网络异常，重新检查登录状态
      setTimeout(() => {
        this.checkLoginStatus()
      }, 2000)
    } finally {
      this.setData({ loading: false })
    }
  },

  // 更新统计数据
  // 更新统计数据 - 与订单状态标签页完全对应
  updateStats() {
    const { orders } = this.data
    
    // 按照标签页逻辑统计各状态数量
    const stats = {
      total: orders.length,
      
      // 待处理 = 待接单（waiting_team标签页逻辑）
      pending: orders.filter(order => 
        ['pending', 'waiting_team'].includes(order.status)
      ).length,
      
      // 进行中 = 已接单 + 查勘中 + 设计中 + 已报价 + 施工中 + 验收中
      inProgress: orders.filter(order => 
        ['accepted', 'team_accepted', 'confirmed', 'surveying', 'designing', 'quoted', 'in_progress', 'testing'].includes(order.status)
      ).length,
      
      // 已完成
      completed: orders.filter(order => 
        order.status === 'completed'
      ).length,
      
      // 已取消
      cancelled: orders.filter(order => 
        order.status === 'cancelled'
      ).length
    }
    
    console.log('📊 统计数据更新:', stats)
    this.setData({ stats })
  },

  // 更新标签计数
  updateTabCounts() {
    const { orders } = this.data
    
    const tabs = this.data.tabs.map(tab => {
      const count = this.getOrderCountByStatus(orders, tab.key)
      return {
        ...tab,
        count: count
      }
    })
    
    this.setData({ 
      tabs: tabs
    })
  },

  // 根据状态获取订单数量
  getOrderCountByStatus(orders, status) {
    if (status === 'all') {
      return orders.length
    } else if (status === 'team_accepted') {
      // "已接单"标签包含accepted、team_accepted和confirmed状态
      return orders.filter(order => 
        ['accepted', 'team_accepted', 'confirmed'].includes(order.status)
      ).length
    } else if (status === 'waiting_team') {
      // "等待接单"标签包含pending和waiting_team状态
      return orders.filter(order => 
        ['pending', 'waiting_team'].includes(order.status)
      ).length
    } else {
      // 其他状态直接按状态计数
      return orders.filter(order => order.status === status).length
    }
  },

  // 获取服务类目信息 - 智能匹配和优化显示
  getServiceCategoryInfo(order) {
    const { serviceCategoryMap } = this.data
    let categoryKey = 'default'
    let categoryInfo = serviceCategoryMap.default

    // 检查输入参数
    if (!order) {
      console.warn('⚠️ getServiceCategoryInfo: order参数为空')
      return {
        key: categoryKey,
        name: categoryInfo.name,
        icon: categoryInfo.icon,
        color: categoryInfo.color
      }
    }

    // 1. 优先使用 serviceCategoryCode（新的标准字段）
    if (order.serviceCategoryCode && serviceCategoryMap[order.serviceCategoryCode]) {
      categoryKey = order.serviceCategoryCode
      categoryInfo = serviceCategoryMap[order.serviceCategoryCode]
    }
    // 2. 使用 serviceType 进行匹配
    else if (order.serviceType) {
      const serviceType = order.serviceType.toLowerCase()
      
      // 智能匹配服务类型
      if (serviceType.includes('market') || serviceType.includes('市场')) {
        categoryKey = 'sme_market'
      } else if (serviceType.includes('info') || serviceType.includes('信息') || serviceType.includes('系统')) {
        categoryKey = 'info_integration'
      } else if (serviceType.includes('engineering') || serviceType.includes('工程') || serviceType.includes('施工')) {
        categoryKey = 'engineering'
      } else if (serviceType.includes('network') || serviceType.includes('网络') || serviceType.includes('维护')) {
        categoryKey = 'network_maintenance'
      } else if (serviceType.includes('smart') || serviceType.includes('智能') || serviceType.includes('家居')) {
        categoryKey = 'smart_home'
      } else if (serviceType.includes('measure') || serviceType.includes('计量') || serviceType.includes('检测')) {
        categoryKey = 'measurement'
      } else if (serviceType.includes('material') || serviceType.includes('材料') || serviceType.includes('设备')) {
        categoryKey = 'materials'
      } else if (serviceType.includes('team') || serviceType.includes('队伍') || serviceType.includes('人员')) {
        categoryKey = 'construction_team'
      } else if (serviceType.includes('home') || serviceType.includes('家居') || serviceType.includes('家庭')) {
        categoryKey = 'home_service'
      } else if (serviceType.includes('repair') || serviceType.includes('维修') || serviceType.includes('修理')) {
        categoryKey = 'repair_service'
      } else if (serviceType.includes('decoration') || serviceType.includes('装修') || serviceType.includes('装饰')) {
        categoryKey = 'decoration'
      } else if (serviceType.includes('clean') || serviceType.includes('清洁') || serviceType.includes('保洁')) {
        categoryKey = 'cleaning'
      } else if (serviceType.includes('appliance') || serviceType.includes('家电') || serviceType.includes('电器')) {
        categoryKey = 'appliance'
      } else if (serviceType.includes('plumb') || serviceType.includes('水电') || serviceType.includes('管道')) {
        categoryKey = 'plumbing'
      }
      
      categoryInfo = serviceCategoryMap[categoryKey] || serviceCategoryMap.default
    }

    return {
      key: categoryKey,
      name: categoryInfo.name,
      icon: categoryInfo.icon,
      color: categoryInfo.color
    }
  },

  // 获取服务项目名称
  getServiceProjectName(order) {
    // 优先级：serviceProject > serviceInfo.title > service.title > serviceTypeLabel > serviceType
    return order.serviceProject || 
           (order.serviceInfo && order.serviceInfo.title) || 
           (order.service && order.service.title) || 
           order.serviceTypeLabel || 
           order.serviceType || 
           '未指定服务'
  },

  // 获取服务图片
  getServiceImage(order) {
    // 优先级：service.image > serviceInfo.image > serviceImage > 根据分类默认图片
    let image = null
    
    if (order.service && order.service.image) {
      image = order.service.image
    } else if (order.serviceInfo && order.serviceInfo.image) {
      image = order.serviceInfo.image
    } else if (order.serviceImage) {
      image = order.serviceImage
    } else if (order.image) {
      image = order.image
    }
    
    // 如果没有图片，根据服务分类返回默认图片
    if (!image) {
      const categoryInfo = this.getServiceCategoryInfo(order)
      const defaultImages = {
        'sme_market': 'https://images.unsplash.com/photo-1544197150-b99a580bb7a8?w=400&h=300&fit=crop',
        'info_integration': 'https://images.unsplash.com/photo-1551434678-e076c223a692?w=400&h=300&fit=crop',
        'engineering': 'https://images.unsplash.com/photo-1541888946425-d81bb19240f5?w=400&h=300&fit=crop',
        'network_maintenance': 'https://images.unsplash.com/photo-1558494949-ef010cbdcc31?w=400&h=300&fit=crop',
        'smart_home': 'https://images.unsplash.com/photo-1558618666-fcd25c85cd64?w=400&h=300&fit=crop',
        'measurement': 'https://images.unsplash.com/photo-1581092160562-40aa08e78837?w=400&h=300&fit=crop',
        'materials': 'https://images.unsplash.com/photo-1586864387967-d02ef85d93e8?w=400&h=300&fit=crop',
        'construction_team': 'https://images.unsplash.com/photo-1504307651254-35680f356dfd?w=400&h=300&fit=crop',
        'home_service': 'https://images.unsplash.com/photo-1558618666-fcd25c85cd64?w=400&h=300&fit=crop',
        'repair_service': 'https://images.unsplash.com/photo-1581092160562-40aa08e78837?w=400&h=300&fit=crop',
        'decoration': 'https://images.unsplash.com/photo-1586023492125-27b2c045efd7?w=400&h=300&fit=crop',
        'cleaning': 'https://images.unsplash.com/photo-1582735689369-4fe89db7114c?w=400&h=300&fit=crop',
        'appliance': 'https://images.unsplash.com/photo-1558618666-fcd25c85cd64?w=400&h=300&fit=crop',
        'plumbing': 'https://images.unsplash.com/photo-1581092918056-0c4c3acd3789?w=400&h=300&fit=crop',
        'default': 'https://images.unsplash.com/photo-1551434678-e076c223a692?w=400&h=300&fit=crop'
      }
      image = defaultImages[categoryInfo.key] || defaultImages.default
    }
    
    return image
  },

  // 服务图片加载成功
  onServiceImageLoad(e) {
    console.log('✅ 服务图片加载成功')
  },

  // 服务图片加载失败
  onServiceImageError(e) {
    console.log('❌ 服务图片加载失败:', e.detail)
    // 可以设置默认图片或隐藏图片容器
  },

  // 复制订单编号
  copyOrderId(e) {
    const { id } = e.currentTarget.dataset
    if (!id) {
      wx.showToast({
        title: '订单编号不存在',
        icon: 'none'
      })
      return
    }

    wx.setClipboardData({
      data: id,
      success: () => {
        wx.showToast({
          title: '订单编号已复制',
          icon: 'success',
          duration: 1500
        })
      },
      fail: () => {
        wx.showToast({
          title: '复制失败',
          icon: 'none'
        })
      }
    })
  },

  // 切换标签
  switchTab(e) {
    const { tab } = e.currentTarget.dataset
    
    if (tab === this.data.activeTab) return
    
    // 严格检查登录状态
    if (!this.requireLogin()) {
      return
    }
    
    console.log('🔄 切换标签:', tab)
    
    this.setData({ 
      activeTab: tab,
      page: 0,
      hasMore: true,
      orders: [], // 清空现有订单，重新开始懒加载
      filteredOrders: []
    })
    
    // 滚动到目标标签页
    this.scrollToTab(tab)
    
    // 重新加载订单数据（首次加载5条）
    this.loadOrders(true, 0)
  },

  // 显示进行中状态菜单
  showInProgressMenu() {
    if (!this.requireLogin()) {
      return
    }
    
    const inProgressTabs = [
      { key: 'team_accepted', label: '已接单' },
      { key: 'surveying', label: '查勘中' },
      { key: 'designing', label: '设计中' },
      { key: 'quoted', label: '已报价' },
      { key: 'in_progress', label: '施工中' },
      { key: 'testing', label: '验收中' }
    ]
    
    const itemList = inProgressTabs.map(tab => tab.label)
    
    wx.showActionSheet({
      itemList: itemList,
      success: (res) => {
        const selectedTab = inProgressTabs[res.tapIndex]
        console.log('📋 选择进行中状态:', selectedTab.label)
        
        this.setData({
          activeTab: selectedTab.key,
          page: 0,
          hasMore: true,
          orders: [], // 清空现有订单，重新开始懒加载
          filteredOrders: []
        })
        
        // 滚动到目标标签页
        this.scrollToTab(selectedTab.key)
        
        // 重新加载订单数据
        this.loadOrders(true, 0)
      },
      fail: (res) => {
        console.log('❌ 取消选择进行中状态')
      }
    })
  },

  // 过滤订单 - 与施工队伍页面状态完全对应
  filterOrders() {
    const { orders, activeTab } = this.data
    let filteredOrders = orders

    if (activeTab !== 'all') {
      if (activeTab === 'team_accepted') {
        // "已接单"标签包含accepted、team_accepted和confirmed状态
        filteredOrders = orders.filter(order => 
          ['accepted', 'team_accepted', 'confirmed'].includes(order.status)
        )
      } else if (activeTab === 'waiting_team') {
        // "等待接单"标签包含pending和waiting_team状态
        filteredOrders = orders.filter(order => 
          ['pending', 'waiting_team'].includes(order.status)
        )
      } else {
        // 其他状态直接按状态筛选
        filteredOrders = orders.filter(order => order.status === activeTab)
      }
    }

    this.setData({ filteredOrders })
  },

  // 查看订单详情
  viewOrderDetail(e) {
    if (!this.requireLogin()) {
      return
    }
    
    const { id } = e.currentTarget.dataset
    wx.navigateTo({
      url: `/pages/order-detail/order-detail?id=${id}`
    })
  },

  // 更新订单状态
  async updateOrderStatus(e) {
    if (!this.requireLogin()) {
      return
    }
    
    const { id, status } = e.currentTarget.dataset
    
    // 根据当前状态提供合适的下一步状态选项
    const getStatusOptions = (currentStatus) => {
      const allOptions = [
        { key: 'confirmed', label: '确认订单' },
        { key: 'surveying', label: '开始查勘' },
        { key: 'designing', label: '开始设计' },
        { key: 'quoted', label: '完成报价' },
        { key: 'waiting_team', label: '等待施工队伍接单' },
        { key: 'team_accepted', label: '施工队伍已接单' },
        { key: 'team_preparing', label: '施工队伍准备中' },
        { key: 'team_on_site', label: '施工队伍到达现场' },
        { key: 'in_progress', label: '开始施工' },
        { key: 'paused', label: '暂停施工' },
        { key: 'testing', label: '开始验收' },
        { key: 'completed', label: '完成订单' },
        { key: 'cancelled', label: '取消订单' }
      ]
      
      // 根据当前状态返回可选的下一步状态
      switch (currentStatus) {
        case 'pending':
          return [
            { key: 'confirmed', label: '确认订单' },
            { key: 'cancelled', label: '取消订单' }
          ]
        case 'confirmed':
          return [
            { key: 'surveying', label: '开始查勘' },
            { key: 'waiting_team', label: '等待施工队伍接单' },
            { key: 'cancelled', label: '取消订单' }
          ]
        case 'surveying':
          return [
            { key: 'designing', label: '开始设计' },
            { key: 'cancelled', label: '取消订单' }
          ]
        case 'designing':
          return [
            { key: 'quoted', label: '完成报价' },
            { key: 'cancelled', label: '取消订单' }
          ]
        case 'quoted':
          return [
            { key: 'waiting_team', label: '等待施工队伍接单' },
            { key: 'in_progress', label: '开始施工' },
            { key: 'cancelled', label: '取消订单' }
          ]
        case 'waiting_team':
          return [
            { key: 'team_accepted', label: '施工队伍已接单' },
            { key: 'reassigning', label: '重新分配队伍' },
            { key: 'cancelled', label: '取消订单' }
          ]
        case 'team_accepted':
          return [
            { key: 'team_preparing', label: '施工队伍准备中' },
            { key: 'team_on_site', label: '施工队伍到达现场' },
            { key: 'cancelled', label: '取消订单' }
          ]
        case 'team_preparing':
          return [
            { key: 'team_on_site', label: '施工队伍到达现场' },
            { key: 'cancelled', label: '取消订单' }
          ]
        case 'team_on_site':
          return [
            { key: 'in_progress', label: '开始施工' },
            { key: 'cancelled', label: '取消订单' }
          ]
        case 'in_progress':
          return [
            { key: 'paused', label: '暂停施工' },
            { key: 'testing', label: '开始验收' },
            { key: 'cancelled', label: '取消订单' }
          ]
        case 'paused':
          return [
            { key: 'in_progress', label: '恢复施工' },
            { key: 'cancelled', label: '取消订单' }
          ]
        case 'testing':
          return [
            { key: 'completed', label: '完成订单' },
            { key: 'in_progress', label: '返回施工' },
            { key: 'cancelled', label: '取消订单' }
          ]
        case 'rejected':
          return [
            { key: 'reassigning', label: '重新分配队伍' },
            { key: 'cancelled', label: '取消订单' }
          ]
        case 'reassigning':
          return [
            { key: 'waiting_team', label: '等待施工队伍接单' },
            { key: 'cancelled', label: '取消订单' }
          ]
        default:
          return allOptions.slice(0, 5) // 默认显示前几个基础状态
      }
    }
    
    const statusOptions = getStatusOptions(status)

    wx.showActionSheet({
      itemList: statusOptions.map(option => option.label),
      success: async (res) => {
        const selectedStatus = statusOptions[res.tapIndex]
        
        wx.showModal({
          title: '确认操作',
          content: `确定要${selectedStatus.label}吗？`,
          success: async (modalRes) => {
            if (modalRes.confirm) {
              await this.performStatusUpdate(id, selectedStatus.key, selectedStatus.label)
            }
          }
        })
      }
    })
  },

  // 执行状态更新
  async performStatusUpdate(orderId, newStatus, statusLabel) {
    wx.showLoading({ title: '更新中...' })

    try {
      const result = await wx.cloud.callFunction({
        name: 'businessManager',
        data: {
          action: 'updateOrderStatus',
          data: {
            orderId: orderId,
            status: newStatus,
            note: `手动更新：${statusLabel}`
          }
        }
      })

      wx.hideLoading()

      if (result.result.success) {
        wx.showToast({
          title: '更新成功',
          icon: 'success'
        })
        
        // 刷新数据
        this.loadOrders()
      } else {
        wx.showToast({
          title: result.result.error || '更新失败',
          icon: 'none'
        })
      }
    } catch (error) {
      wx.hideLoading()
      console.error('更新订单状态失败:', error)
      wx.showToast({
        title: '网络错误，请重试',
        icon: 'none'
      })
    }
  },

  // 联系客户
  contactCustomer(e) {
    if (!this.requireLogin()) {
      return
    }
    
    const phone = e.currentTarget.dataset.phone
    if (!phone) {
      wx.showToast({
        title: '无联系电话',
        icon: 'none'
      })
      return
    }

    wx.makePhoneCall({
      phoneNumber: phone,
      success: () => {

      },
      fail: (error) => {
        console.error('📞 拨打客户电话失败:', error)
        wx.showToast({
          title: '拨打失败',
          icon: 'none'
        })
      }
    })
  },

  // 联系施工队伍
  contactTeam(e) {
    if (!this.requireLogin()) {
      return
    }
    
    const phone = e.currentTarget.dataset.phone
    if (!phone) {
      wx.showToast({
        title: '无联系电话',
        icon: 'none'
      })
      return
    }

    wx.makePhoneCall({
      phoneNumber: phone,
      success: () => {

      },
      fail: (error) => {
        console.error('📞 拨打施工队伍电话失败:', error)
        wx.showToast({
          title: '拨打失败',
          icon: 'none'
        })
      }
    })
  },

  // 格式化日期
  formatDate(dateStr) {
    if (!dateStr) return ''
    
    try {
      let date
      
      // 处理不同的日期格式
      if (typeof dateStr === 'string') {
        date = new Date(dateStr)
      } else if (dateStr instanceof Date) {
        date = dateStr
      } else if (typeof dateStr === 'number') {
        date = new Date(dateStr)
      } else {
        date = new Date(String(dateStr))
      }
      
      // 检查日期是否有效
      if (isNaN(date.getTime())) {
        console.warn('❌ 无效的日期格式:', dateStr)
        return String(dateStr)
      }
      
      const now = new Date()
      const diff = now - date
      const days = Math.floor(diff / (1000 * 60 * 60 * 24))
      
      if (days === 0) {
        const hours = Math.floor(diff / (1000 * 60 * 60))
        if (hours === 0) {
          const minutes = Math.floor(diff / (1000 * 60))
          return minutes <= 0 ? '刚刚' : `${minutes}分钟前`
        }
        return `${hours}小时前`
      } else if (days === 1) {
        return '昨天'
      } else if (days < 7) {
        return `${days}天前`
      } else {
        // 手动格式化，确保兼容性
        const year = date.getFullYear()
        const month = String(date.getMonth() + 1).padStart(2, '0')
        const day = String(date.getDate()).padStart(2, '0')
        return `${year}年${month}月${day}日`
      }
    } catch (error) {
      console.error('❌ 格式化日期失败:', error, '原始数据:', dateStr)
      return String(dateStr)
    }
  },

  // 格式化创建时间 - 统一显示年月日时分格式
  formatCreateTime(dateStr) {
    if (!dateStr) {
      return '时间未知'
    }
    
    try {
      let date
      
      // 处理不同的日期格式
      if (typeof dateStr === 'string') {
        date = new Date(dateStr)
      } else if (dateStr instanceof Date) {
        date = dateStr
      } else if (typeof dateStr === 'number') {
        date = new Date(dateStr)
      } else {
        date = new Date(String(dateStr))
      }
      
      // 检查日期是否有效
      if (isNaN(date.getTime())) {
        console.warn('⚠️ 无效的时间格式:', dateStr)
        return '时间格式错误'
      }
      
      // 手动格式化，确保兼容性
      const year = date.getFullYear()
      const month = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      const hours = String(date.getHours()).padStart(2, '0')
      const minutes = String(date.getMinutes()).padStart(2, '0')
      
      return `${year}年${month}月${day}日 ${hours}:${minutes}`
      
    } catch (error) {
      console.error('❌ 时间格式化失败:', error, '原始时间:', dateStr)
      return '时间解析失败'
    }
  },



  // 获取状态信息
  getStatusInfo(status) {
    if (!status) {
      return { text: '待接单', color: '#FF6B35', bgColor: 'rgba(255, 107, 53, 0.1)' } // 默认状态
    }
    
    // 转换为小写进行匹配
    const lowerStatus = String(status).toLowerCase()
    
    // 先尝试直接匹配
    if (this.data.statusMap[status]) {
      return this.data.statusMap[status]
    }
    
    // 再尝试小写匹配
    if (this.data.statusMap[lowerStatus]) {
      return this.data.statusMap[lowerStatus]
    }
    
    // 智能识别英文状态关键词
    if (lowerStatus.includes('accept') || lowerStatus.includes('confirm')) {
      return { text: '已接单', color: '#2196F3', bgColor: 'rgba(33, 150, 243, 0.1)' }
    } else if (lowerStatus.includes('wait') || lowerStatus.includes('pend')) {
      return { text: '待接单', color: '#FF6B35', bgColor: 'rgba(255, 107, 53, 0.1)' }
    } else if (lowerStatus.includes('progress') || lowerStatus.includes('working') || lowerStatus.includes('construction')) {
      return { text: '施工中', color: '#2196F3', bgColor: 'rgba(33, 150, 243, 0.1)' }
    } else if (lowerStatus.includes('complete') || lowerStatus.includes('finish') || lowerStatus.includes('done')) {
      return { text: '已完成', color: '#4CAF50', bgColor: 'rgba(76, 175, 80, 0.1)' }
    } else if (lowerStatus.includes('cancel') || lowerStatus.includes('reject')) {
      return { text: '已取消', color: '#F44336', bgColor: 'rgba(244, 67, 54, 0.1)' }
    } else if (lowerStatus.includes('survey') || lowerStatus.includes('inspect')) {
      return { text: '查勘中', color: '#9C27B0', bgColor: 'rgba(156, 39, 176, 0.1)' }
    } else if (lowerStatus.includes('design')) {
      return { text: '设计中', color: '#673AB7', bgColor: 'rgba(103, 58, 183, 0.1)' }
    } else if (lowerStatus.includes('quot') || lowerStatus.includes('price')) {
      return { text: '已报价', color: '#3F51B5', bgColor: 'rgba(63, 81, 181, 0.1)' }
    } else if (lowerStatus.includes('test') || lowerStatus.includes('check')) {
      return { text: '验收中', color: '#00BCD4', bgColor: 'rgba(0, 188, 212, 0.1)' }
    } else {
      // 如果都匹配不到，返回默认状态
      return { text: '待接单', color: '#666', bgColor: 'rgba(102, 102, 102, 0.1)' }
    }
  },

  // 创建新订单
  createNewOrder() {
    wx.navigateTo({
      url: '/pages/booking/booking'
    })
  },

  // 搜索订单
  searchOrders(e) {
    if (!this.requireLogin()) {
      return
    }
    
    const keyword = e.detail.value.trim()
    this.setData({ searchKeyword: keyword })
    
    if (!keyword) {
      this.filterOrders()
      return
    }

    const { orders } = this.data
    const filteredOrders = orders.filter(order => {
      // 基本信息搜索
      const basicMatch =
        order.customerName.includes(keyword) ||
        order.phone.includes(keyword) ||
        order.id.includes(keyword) ||
        (order.company && order.company.includes(keyword))

      // 服务项目搜索
      const serviceMatch =
        (order.serviceProject && order.serviceProject.includes(keyword)) ||
        (order.serviceType && order.serviceType.includes(keyword)) ||
        (order.serviceInfo && order.serviceInfo.title && order.serviceInfo.title.includes(keyword)) ||
        (order.service && order.service.title && order.service.title.includes(keyword))

      return basicMatch || serviceMatch
    })



    this.setData({ filteredOrders })
  },

  // 清除搜索
  clearSearch() {
    if (!this.requireLogin()) {
      return
    }
    
    this.setData({ searchKeyword: '' })
    this.filterOrders()
  },

  // 导出订单数据
  exportOrders() {
    if (!this.requireLogin()) {
      return
    }
    
    if (this.data.orders.length === 0) {
      wx.showToast({
        title: '暂无数据可导出',
        icon: 'none'
      })
      return
    }

    wx.showModal({
      title: '导出数据',
      content: '是否导出当前订单数据？数据将保存到相册中。',
      success: (res) => {
        if (res.confirm) {
          this.performExport()
        }
      }
    })
  },

  // 显示筛选菜单
  showFilterMenu() {
    if (!this.requireLogin()) {
      return
    }
    
    this.setData({ showFilterMenu: true })
  },

  // 隐藏筛选菜单
  hideFilterMenu() {
    this.setData({ showFilterMenu: false })
  },

  // 执行导出
  async performExport() {
    wx.showLoading({ title: '导出中...' })
    
    try {
      // 这里可以调用云函数生成Excel或图片
      // 暂时使用简单的文本导出
      const exportData = this.data.orders.map(order => {
        const status = this.getStatusInfo(order.status)
        return `订单号: ${order.id}\n客户: ${order.customerName}\n电话: ${order.phone}\n状态: ${status.text}\n创建时间: ${this.formatDate(order.createTime)}\n---`
      }).join('\n')

      // 复制到剪贴板
      wx.setClipboardData({
        data: exportData,
        success: () => {
          wx.hideLoading()
          wx.showToast({
            title: '数据已复制到剪贴板',
            icon: 'success'
          })
        }
      })
    } catch (error) {
      wx.hideLoading()
      console.error('导出失败:', error)
      wx.showToast({
        title: '导出失败',
        icon: 'none'
      })
    }
  },

  // 获取空状态标题
  getEmptyStateTitle() {
    const { activeTab, searchKeyword } = this.data
    
    if (searchKeyword) {
      return '未找到相关订单'
    }
    
    const titleMap = {
      'all': '暂无订单记录',
      'pending': '暂无待处理订单',
      'confirmed': '暂无已确认订单',
      'in_progress': '暂无进行中订单',
      'completed': '暂无已完成订单'
    }
    
    return titleMap[activeTab] || '暂无订单记录'
  },

  // 获取空状态副标题
  getEmptyStateSubtitle() {
    const { activeTab, searchKeyword } = this.data
    
    if (searchKeyword) {
      return '尝试调整搜索关键词或筛选条件'
    }
    
    const subtitleMap = {
      'all': '您还没有提交过任何预约订单\n可以前往服务页面进行预约',
      'pending': '当前没有等待处理的订单',
      'confirmed': '当前没有已确认的订单',
      'in_progress': '当前没有正在进行的订单',
      'completed': '当前没有已完成的订单'
    }
    
    return subtitleMap[activeTab] || '您还没有提交过任何预约订单'
  },

  // 回到顶部
  scrollToTop() {
    wx.pageScrollTo({
      scrollTop: 0,
      duration: 300
    })
  },

  // 获取下一步操作文本
  getNextAction(status) {
    const actionMap = {
      // 基础状态
      'pending': '确认订单',
      'confirmed': '开始查勘',
      'surveying': '完成查勘',
      'designing': '生成报价',
      'quoted': '开始施工',
      
      // 施工队伍相关状态
      'waiting_team': '等待接单',
      'team_accepted': '队伍已接单',
      'team_preparing': '准备施工',
      'team_on_site': '到达现场',
      'in_progress': '申请验收',
      'paused': '恢复施工',
      'testing': '完成验收',
      'completed': '查看详情',
      'cancelled': '重新提交',
      
      // 特殊状态
      'rejected': '重新分配',
      'reassigning': '等待分配'
    }
    
    return actionMap[status] || '查看详情'
  },

  // 显示订单菜单
  showOrderMenu(e) {
    if (!this.requireLogin()) {
      return
    }
    
    const orderId = e.currentTarget.dataset.id
    this.setData({
      showOrderMenu: true,
      selectedOrderId: orderId
    })
  },

  // 隐藏订单菜单
  hideOrderMenu() {
    this.setData({
      showOrderMenu: false,
      selectedOrderId: ''
    })
  },

  // 编辑订单
  editOrder(e) {
    const orderId = e.currentTarget.dataset.id
    this.hideOrderMenu()
    
    wx.showToast({
      title: '编辑功能开发中',
      icon: 'none'
    })
  },

  // 复制订单
  duplicateOrder(e) {
    const orderId = e.currentTarget.dataset.id
    this.hideOrderMenu()
    
    wx.showToast({
      title: '复制功能开发中',
      icon: 'none'
    })
  },

  // 导出单个订单
  exportOrder(e) {
    const orderId = e.currentTarget.dataset.id
    this.hideOrderMenu()
    
    wx.showToast({
      title: '导出功能开发中',
      icon: 'none'
    })
  },

  // 删除订单
  deleteOrder(e) {
    const orderId = e.currentTarget.dataset.id
    this.hideOrderMenu()
    
    wx.showModal({
      title: '确认删除',
      content: '确定要删除这个订单吗？此操作不可撤销。',
      confirmColor: '#ff4444',
      success: (res) => {
        if (res.confirm) {
          wx.showToast({
            title: '删除功能开发中',
            icon: 'none'
          })
        }
      }
    })
  },

  // 改变排序方式
  changeSortBy(e) {
    const sortBy = e.currentTarget.dataset.sort
    this.setData({ sortBy })
  },

  // 改变时间范围
  changeTimeRange(e) {
    const timeRange = e.currentTarget.dataset.range
    this.setData({ timeRange })
  },

  // 重置筛选条件
  resetFilters() {
    this.setData({
      sortBy: 'createTime',
      sortOrder: 'desc',
      timeRange: 'all'
    })
  },

  // 应用筛选条件
  applyFilters() {
    this.hideFilterMenu()
    this.filterAndSortOrders()
  },

  // 筛选和排序订单
  filterAndSortOrders() {
    let { orders, timeRange, sortBy, sortOrder } = this.data
    
    // 🚨 注意：这里使用的是预处理过的orders数据，包含formattedCreateTime等字段
    
    // 时间筛选
    if (timeRange !== 'all') {
      const now = new Date()
      const filteredOrders = orders.filter(order => {
        const orderDate = new Date(order.createTime)
        
        switch (timeRange) {
          case 'today':
            return orderDate.toDateString() === now.toDateString()
          case 'week':
            const weekStart = new Date(now.getFullYear(), now.getMonth(), now.getDate() - now.getDay())
            return orderDate >= weekStart
          case 'month':
            return orderDate.getMonth() === now.getMonth() && orderDate.getFullYear() === now.getFullYear()
          case 'quarter':
            const quarter = Math.floor(now.getMonth() / 3)
            const quarterStart = new Date(now.getFullYear(), quarter * 3, 1)
            return orderDate >= quarterStart
          default:
            return true
        }
      })
      orders = filteredOrders
    }
    
    // 排序
    orders.sort((a, b) => {
      let comparison = 0
      
      switch (sortBy) {
        case 'createTime':
        case 'updateTime':
          comparison = new Date(a[sortBy]) - new Date(b[sortBy])
          break
        case 'customerName':
          comparison = a.customerName.localeCompare(b.customerName)
          break
        case 'status':
          comparison = a.status.localeCompare(b.status)
          break
        default:
          comparison = 0
      }
      
      return sortOrder === 'desc' ? -comparison : comparison
    })
    
    this.setData({ filteredOrders: orders })
    this.updateTabCounts()
  },

  // 滚动到指定标签页
  scrollToTab(targetTab) {
    if (!targetTab) return
    
    console.log('📱 滚动到标签页:', targetTab)
    
    // 延迟执行，确保DOM已更新
    setTimeout(() => {
      // 获取标签页的索引
      const tabIndex = this.data.tabs.findIndex(tab => tab.key === targetTab)
      if (tabIndex === -1) {
        console.log('⚠️ 未找到目标标签页:', targetTab)
        return
      }
      
      console.log('📍 目标标签页索引:', tabIndex)
      
      // 创建查询对象
      const query = wx.createSelectorQuery().in(this)
      
      // 查询scroll-view容器
      query.select('.tabs').boundingClientRect()
      
      // 查询所有标签项
      query.selectAll('.tab-item').boundingClientRect()
      
      query.exec((res) => {
        if (!res[0] || !res[1] || !res[1][tabIndex]) {
          console.log('⚠️ 无法获取标签页位置信息')
          return
        }
        
        const scrollViewRect = res[0]
        const tabRects = res[1]
        const targetTabRect = tabRects[tabIndex]
        
        console.log('📊 滚动容器信息:', {
          width: scrollViewRect.width,
          left: scrollViewRect.left
        })
        
        console.log('📊 目标标签信息:', {
          left: targetTabRect.left,
          width: targetTabRect.width,
          right: targetTabRect.right
        })
        
        // 计算目标标签相对于滚动容器的位置
        const tabRelativeLeft = targetTabRect.left - scrollViewRect.left
        const tabRelativeRight = targetTabRect.right - scrollViewRect.left
        
        console.log('📊 相对位置:', {
          left: tabRelativeLeft,
          right: tabRelativeRight,
          containerWidth: scrollViewRect.width
        })
        
        // 判断是否需要滚动
        let scrollLeft = 0
        let needScroll = false
        
        if (tabRelativeLeft < 0) {
          // 标签在左侧被遮挡，滚动到左边
          scrollLeft = targetTabRect.left - scrollViewRect.left - 20 // 留20rpx边距
          needScroll = true
          console.log('⬅️ 标签被左侧遮挡，需要向左滚动')
        } else if (tabRelativeRight > scrollViewRect.width) {
          // 标签在右侧被遮挡，滚动到右边
          scrollLeft = targetTabRect.right - scrollViewRect.left - scrollViewRect.width + 20 // 留20rpx边距
          needScroll = true
          console.log('➡️ 标签被右侧遮挡，需要向右滚动')
        } else {
          console.log('✅ 标签已在可见区域，无需滚动')
          return
        }
        
        if (!needScroll) return
        
        // 确保滚动距离不为负数
        scrollLeft = Math.max(0, scrollLeft)
        
        console.log('📱 执行滚动，scrollLeft:', scrollLeft)
        
        // 使用scroll-view的scroll-left属性进行滚动
        this.setData({
          tabScrollLeft: scrollLeft
        })
        
        console.log('✅ 标签页滚动设置完成')
      })
    }, 100)
  }
})
